package utils;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;

import entities.ObjectForSend;

public class HTTPMethod {
	public static HttpGet buildGET(String url,List<NameValuePair> headers) {
		HttpGet getMethod = new HttpGet(url);
		for(NameValuePair header : headers) {
			getMethod.addHeader(header.getName(), header.getValue());
		}
		
		return getMethod;
	}
	
	public static HttpPost buildPost(String url,List<NameValuePair> headers, List<ObjectForSend> content, boolean isMultipart) {
		HttpPost postMethod = new HttpPost(url);
		for(NameValuePair header : headers) {
			postMethod.addHeader(header.getName(), header.getValue());
		}
		if(!isMultipart){
//			List<NameValuePair> entity = new ArrayList<NameValuePair>();
			for(ObjectForSend element:content) {
				postMethod.setEntity((StringEntity)element.getContent());
//				entity.add(new BasicNameValuePair(element.getNameOfContent(),(String)element.getContent()));
			}
			
		}
//				postMethod.setEntity(new UrlEncodedFormEntity(content));
		else {
			MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
			for(ObjectForSend element:content) {
				if(element.getType().equals(ObjectForSend.FILE_CONSTANT_TYPE)) {
					entity.addPart("image", new FileBody((File)element.getContent()));
				} else if(element.getType().equals(ObjectForSend.STRING_CONSTANT_TYPE)){
					try {
						entity.addPart(element.getNameOfContent(), new StringBody((String)element.getContent()));
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
					}
				}
			}
			postMethod.setEntity(entity);
		}
		return postMethod;
	}
}
